/*************************************************************************
 * CS516 Software Engineering
 * Group Project: Android Finance Management System
 * AddTransaction.java
 * The tab page to add transaction
 *************************************************************************/
package com.svu.se.group3;

import java.text.NumberFormat;
import java.util.Calendar;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Toast;
/**
 * (add your name below)
 * @author A2303 Lei Jiang 
 */
public class AddTransaction extends Activity {
	// attributes
	private EditText mProductName;
	private EditText mCategory;
	private EditText mQuantity;
	private EditText mPrice;
	private Button mDateDisplay;
	private Button mSubmit;
	private Button mClear;
	private int mYear;
    private int mMonth;
    private int mDay;
	static final int DATE_DIALOG_ID = 0;
	
	// the callback received when the user "sets" the date in the dialog
    private DatePickerDialog.OnDateSetListener mDateSetListener =
            new DatePickerDialog.OnDateSetListener() {
    			@Override
    			public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
    				mYear = year;
                    mMonth = monthOfYear;
                    mDay = dayOfMonth;
                    updateDisplay();
                }
            };

    @Override
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.add_transaction);
        
        mProductName = (EditText)findViewById(R.id.prod_name);
        mCategory = (EditText)findViewById(R.id.category);
        mQuantity = (EditText)findViewById(R.id.quantity);
        mPrice = (EditText)findViewById(R.id.price);
        mDateDisplay = (Button)findViewById(R.id.date);
        mSubmit = (Button)findViewById(R.id.submit);
        mClear = (Button)findViewById(R.id.clear);
        final Calendar c = Calendar.getInstance();
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH);

        // display the current date (this method is below)
        updateDisplay();        
        
        // add a click listener to the button
        mDateDisplay.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                showDialog(DATE_DIALOG_ID);
            }
        });
        mSubmit.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                // Create new transaction and save
            	if(validateInput()){
            		/**
            		 * create new transaction and save
            		 * t = new Transaction()
            		 * t.set()...
            		 * t.save()
            		 */
            		Transaction mTrans = new Transaction();
            		mTrans.setmProductName(mProductName.getText().toString());
            		mTrans.setmCategory(mCategory.getText().toString());
            		mTrans.setmPrice(Float.parseFloat(mPrice.getText().toString().replaceAll("[$,.]", ""))/100);
            		mTrans.setmQuantity(Integer.parseInt(mQuantity.getText().toString()));
            		mTrans.setmPurchaseDate(mDateDisplay.getText().toString());
            		mTrans.save();
            		
            		Toast.makeText(v.getContext(), R.string.tab_add_success, Toast.LENGTH_SHORT).show();
            	}else{
            		Toast.makeText(v.getContext(), R.string.tab_add_warning, Toast.LENGTH_SHORT).show();
            	}
            }
        });
        mClear.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                // Clear all previous input
            	mProductName.setText(null);
            	mCategory.setText(null);
            	mQuantity.setText(getResources().getText(R.string.tab_add_default_quantity));
            	mPrice.setText(getResources().getText(R.string.tab_add_default_price));
            	mYear = c.get(Calendar.YEAR);
                mMonth = c.get(Calendar.MONTH);
                mDay = c.get(Calendar.DAY_OF_MONTH);
                updateDisplay();
            }
        });
        mPrice.addTextChangedListener(new PriceWatcher());

    }
	
	// updates the date in the UI
    private void updateDisplay() {
        mDateDisplay.setText(
            new StringBuilder()
                    // Month is 0 based so add 1
                    .append(mYear).append("-")
                    .append(mMonth + 1).append("-")
                    .append(mDay));
    }
	
    // return date dialog
	@Override
	protected Dialog onCreateDialog(int id) {
	    switch (id) {
	    case DATE_DIALOG_ID:
	        return new DatePickerDialog(this,
	                    mDateSetListener,
	                    mYear, mMonth, mDay);
	    }
	    return null;
	}
	
	// validate if input is valid
	private boolean validateInput(){
		if(mProductName.getText().toString().length() == 0) return false;
		if(mCategory.getText().toString().length() == 0) return false;
		if(mQuantity.getText().toString().length() == 0) return false;
		if(mPrice.getText().toString().length() == 0) return false;		
		
		return true;
	}
	
	// TextWatcher to format price
	class PriceWatcher implements TextWatcher{
		private String current = "";

		@Override
		public void afterTextChanged(Editable arg0) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			// TODO Auto-generated method stub
			if(!s.toString().equals(current)){
			   String cleanString = s.toString().replaceAll("[$,.]", "");
			   double parsed = Double.parseDouble(cleanString);
			   String formated = NumberFormat.getCurrencyInstance().format(parsed/100);
			   current = formated;
			   mPrice.setText(formated);
			   mPrice.setSelection(formated.length());
		    }
		}	
	}
}



